import { defineSource } from '../source';
import { ProcessedItem } from '../types'
import { myFetch } from "../utils/fetch"
import logger from '../../framework/config/logger';

interface ZhihuHotItem {
    title_area: {
        text: string;
    };
    excerpt_area: {
        text: string;
    };
    image_area: {
        url: string;
    };
    metrics_area: {
        text: string;
        font_color: string;
        background: string;
        weight: string;
    };
    label_area: {
        type: "trend";
        trend: number;
        night_color: string;
        normal_color: string;
    };
    link: {
        url: string;
    };
}

interface ZhihuResponse {
    data: {
        type: "hot_list_feed";
        style_type: "1";
        feed_specific: {
            answer_count: number;
        };
        target: ZhihuHotItem;
    }[];
}


export default defineSource({
    zhihu: async (): Promise<ProcessedItem[]> => {
        const API_URL = "https://www.zhihu.com/api/v3/feed/topstory/hot-list-web";
        const params = {
            limit: 20,
            desktop: true
        };
        const url = `${API_URL}?${new URLSearchParams(params as any).toString()}`;

        try {
            const res: ZhihuResponse = await myFetch(url);

            return res.data.map((item) => {
                const questionId = item.target.link.url.match(/(\d+)$/)?.[1] ?? item.target.link.url;

                return {
                    id: questionId,
                    title: item.target.title_area.text,
                    url: item.target.link.url,
                    extra: {
                        hot: item.target.metrics_area.text,
                        content: item.target.excerpt_area.text,
                    },
                };
            });
        } catch (error) {
            console.error('获取知乎热榜数据失败:', error);
            throw new Error('Failed to fetch Zhihu hot list');
        }
    },
});